<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">未缴账单管理</h1>
      <div class="header-controls">
        <!-- 通知状态筛选 -->
        <el-select
          v-model="searchForm.notification"
          placeholder="通知状态"
          style="width: 140px; margin-right: 10px"
          clearable
          @change="handleSearch"
          @clear="
            () => {
              searchForm.notification = 0;
              handleSearch();
            }
          "
        >
          <el-option label="全部" :value="0" />
          <el-option label="已通知" :value="1" />
          <el-option label="未通知" :value="2" />
        </el-select>
        <!-- 搜索框 -->
        <el-input
          v-model="searchForm.name"
          placeholder="小区/收费标准/缴费人姓名"
          style="width: 200px; margin-right: 10px"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 操作按钮区域 -->
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button
            type="success"
            :disabled="selectedRows.length === 0"
            @click="handleSendNotification"
          >
            发送通知 ({{ selectedRows.length }})
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-button @click="handleRefresh">刷新</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="cellName" label="小区名称" width="100" />
        <el-table-column
          prop="payer"
          label="缴费人"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="payerType"
          label="缴费人类型"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getPayerTypeTag(row.payerType)">
              {{ getPayerTypeText(row.payerType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="phone"
          label="联系电话"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          prop="email"
          label="邮箱"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="chargestandardName"
          label="收费标准"
          width="120"
          align="center"
        />
        <el-table-column prop="price" label="单价" width="60">
          <template #default="{ row }"> ¥{{ row.price }} </template>
        </el-table-column>
        <el-table-column prop="receivableAmount" label="应收金额" width="90">
          <template #default="{ row }"> ¥{{ row.receivableAmount }} </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="80">
          <template #default="{ row }"> ¥{{ row.totalAmount }} </template>
        </el-table-column>
        <el-table-column
          prop="notification"
          label="通知状态"
          width="90"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="row.notification === 1 ? 'success' : 'warning'">
              {{ row.notification === 1 ? "已通知" : "未通知" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              @click="handleSendSingleNotification(row, $index)"
            >
              通知
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getUnpaidBillList, sendNotification } from "@/api/unpaidBill";
import type { UnpaidBillItem } from "@/api/unpaidBill";

defineOptions({ name: "UnpaidBill" });

// 响应式数据
const loading = ref(false);
const tableData = ref<UnpaidBillItem[]>([]);
const selectedRows = ref<UnpaidBillItem[]>([]);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  name: "",
  notification: 0 as 0 | 1 | 2
});

// 分页
const pagination = reactive({
  page: 1,
  limit: 10
});

// 获取缴费人类型文本
const getPayerTypeText = (type: number) => {
  const typeMap = {
    1: "业主",
    2: "租房人员",
    3: "客户"
  };
  return typeMap[type as keyof typeof typeMap] || "未知";
};

// 获取缴费人类型标签样式
const getPayerTypeTag = (
  type: number
): "success" | "warning" | "info" | "primary" | "danger" => {
  const tagMap: Record<
    number,
    "success" | "warning" | "info" | "primary" | "danger"
  > = {
    1: "success",
    2: "warning",
    3: "info"
  };
  return tagMap[type] || "info";
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page - 1,
      limit: pagination.limit,
      name: searchForm.name,
      notification:
        searchForm.notification === 1 || searchForm.notification === 2
          ? searchForm.notification
          : 0
    };
    const response = await getUnpaidBillList(params);
    if (response.code === 0) {
      tableData.value = response.data;
      total.value = response.data.length; // 由于接口返回的是数组，这里假设总数就是数组长度
    } else {
      ElMessage.error(response.message || "获取数据失败");
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchData();
};

// 重置
const handleReset = () => {
  searchForm.name = "";
  searchForm.notification = 0;
  pagination.page = 1;
  fetchData();
};

// 刷新
const handleRefresh = () => {
  fetchData();
};

// 选择变化
const handleSelectionChange = (selection: UnpaidBillItem[]) => {
  selectedRows.value = selection;
};

// 发送通知
const handleSendNotification = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要发送通知的账单");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要发送通知给选中的 ${selectedRows.value.length} 条账单吗？`,
      "确认发送通知",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    loading.value = true;
    try {
      const ids = selectedRows.value
        .map(row => row.id)
        .filter(id => id !== undefined);
      if (ids.length === 0) {
        ElMessage.warning("选中的账单没有有效的ID");
        return;
      }

      const response = await sendNotification(ids);
      if (response.code === 0) {
        ElMessage.success("通知发送成功！");
        selectedRows.value = [];
        fetchData(); // 刷新数据
      } else {
        ElMessage.error(response.message || "发送通知失败");
      }
    } catch (error) {
      ElMessage.error("发送通知失败");
      console.error(error);
    } finally {
      loading.value = false;
    }
  } catch {
    // 用户取消
  }
};

// 发送单个通知
const handleSendSingleNotification = async (
  row: UnpaidBillItem,
  index: number
) => {
  try {
    await ElMessageBox.confirm(
      `确定要发送通知给 ${row.payer} 吗？`,
      "确认发送通知",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    loading.value = true;
    try {
      const id = row.id;
      if (!id || id <= 0) {
        ElMessage.warning("该账单没有有效的ID");
        return;
      }

      const response = await sendNotification([id]);
      if (response.code === 0) {
        ElMessage.success("通知发送成功！");
        fetchData(); // 刷新数据
      } else {
        ElMessage.error(response.message || "发送通知失败");
      }
    } catch (error) {
      ElMessage.error("发送通知失败");
      console.error(error);
    } finally {
      loading.value = false;
    }
  } catch {
    // 用户取消
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchData();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchData();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.main {
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  margin-bottom: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.content-area {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
  min-height: 400px;
  padding: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.toolbar-left {
  display: flex;
  gap: 10px;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-button--small) {
  padding: 5px 12px;
  font-size: 12px;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 2px;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 4px;
}
</style>
